package com.lzz.bottomencapsulation.customview.selectimage.utils;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.lzz.bottomencapsulation.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 权限获取
 */
public class PermissionUtils {

    private static final String TAG = PermissionUtils.class.getSimpleName();

    public static final int CODE_CAMERA = 0;
    public static final int CODE_READ_EXTERNAL_STORAGE = 1;
    public static final int CODE_WRITE_EXTERNAL_STORAGE = 2;
    /**
     * 权限全部授予
     */
    public static final int CODE_MULTI_PERMISSION = 100;
    /**
     * 取消权限授予
     */
    public static final int CODE_CANCLE = -1;

    public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    public static final String PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission
            .READ_EXTERNAL_STORAGE;
    public static final String PERMISSION_WRITE_EXTERNAL_STORAGE = Manifest.permission
            .WRITE_EXTERNAL_STORAGE;

    private static final String[] pushLivePermissions = {PERMISSION_CAMERA,
            PERMISSION_READ_EXTERNAL_STORAGE, PERMISSION_WRITE_EXTERNAL_STORAGE};

    public interface PermissionGrant {
        void onPermissionGranted(int requestCode);
    }

    /**
     * Requests permission.
     *
     * @param activity
     * @param requestCode request code, e.g. if you need request CAMERA permission,parameters is
     *                    PermissionUtils
     *                    .CODE_CAMERA
     */
    public static void requestPermission(final Activity activity, final int requestCode,
                                         PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }

        Log.i(TAG, "requestPermission requestCode:" + requestCode);
        if (requestCode < 0 || requestCode >= pushLivePermissions.length) {
            Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
            return;
        }

        final String requestPermission = pushLivePermissions[requestCode];

        //如果是6.0以下的手机，ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED，
        // 但是，如果用户关闭了你申请的权限，ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang
        // .RuntimeException: Unknown
        // exception code: 1 msg null)，
        // 你可以使用try{}catch(){},处理异常，也可以判断系统版本，低于23就不申请权限，直接做你想做的。permissionGrant
        // .onPermissionGranted(requestCode);
        if (Build.VERSION.SDK_INT < 23) {
            permissionGrant.onPermissionGranted(requestCode);
            return;
        }

        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
        } catch (RuntimeException e) {
            Toast.makeText(activity, "请开启您的权限", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "RuntimeException:" + e.getMessage());
            return;
        }

        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");


            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
                Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");
                shouldShowRationale(activity, requestCode, requestPermission, permissionGrant);

            } else {
                Log.d(TAG, "requestCameraPermission else");
                ActivityCompat.requestPermissions(activity, new String[]{requestPermission},
                        requestCode);
            }

        } else {
            Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager " + "" +
                    ".PERMISSION_GRANTED");
            permissionGrant.onPermissionGranted(requestCode);
        }
    }

    private static void requestMultiResult(Activity activity, String[] permissions, int[]
            grantResults, PermissionGrant permissionGrant) {

        if (activity == null) {
            return;
        }

        //TODO
        Log.d(TAG, "onRequestPermissionsResult permissions length:" + permissions.length);
        Map<String, Integer> perms = new HashMap<>();

        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            Log.d(TAG, "permissions: [i]:" + i + ", permissions[i]" + permissions[i] + "," +
                    "grantResults[i]:" +
                    grantResults[i]);
            perms.put(permissions[i], grantResults[i]);
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                notGranted.add(permissions[i]);
            }
        }

        if (notGranted.size() == 0) {
//            权限获取成功
            permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION);
        } else {
//            权限未授予
            openSettingActivity(activity, activity.getResources().getString(R.string
                    .ApplicationInformation), permissionGrant);
        }

    }


    /**
     * 一次申请多个权限
     */
    public static void requestMultiPermissions(final Activity activity, final PermissionGrant
            grant) {
        /**
         * 不需要授予权限说明，暂未授予的权限
         */
        final List<String> permissionsList = getNoGrantedPermission(activity, false);
        /**
         * 需要授予说明，暂未授予的权限
         */
        final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);

        if (permissionsList == null || shouldRationalePermissionsList == null) {
            return;
        }

        if (permissionsList.size() > 0) {
            ActivityCompat.requestPermissions(activity, permissionsList.toArray(new
                    String[permissionsList.size()]), CODE_MULTI_PERMISSION);
        } else if (shouldRationalePermissionsList.size() > 0) {

            activity.getResources().getString(R.string
                            .notPermission);

            showMessageOKCancel(activity, activity.getResources().getString(R.string
                    .notPermission), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList
                            .toArray(new String[shouldRationalePermissionsList.size()]),
                            CODE_MULTI_PERMISSION);
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                            取消授予权限
                    grant.onPermissionGranted(CODE_CANCLE);
                }
            });
        } else {
//            权限全部授予
            grant.onPermissionGranted(CODE_MULTI_PERMISSION);
        }

    }


    private static void shouldShowRationale(final Activity activity, final int requestCode, final
    String requestPermission, final PermissionGrant permissionGrant) {
        //TODO
        String[] permissionsHint = activity.getResources().getStringArray(R.array
                .permissions_selectorimg);
        showMessageOKCancel(activity, permissionsHint[requestCode], new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(activity, new String[]{requestPermission},
                        requestCode);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                permissionGrant.onPermissionGranted(CODE_CANCLE);
            }
        });
    }

    private static void showMessageOKCancel(final Activity context, String message,
                                            DialogInterface.OnClickListener okListener,
                                            DialogInterface.OnClickListener noListener) {
        Log.e("弹出框", "弹出框");
        AlertDialog alertDialog = new AlertDialog.Builder(context).setMessage(message)
                .setPositiveButton(context.getResources().getString(R.string.confirm),
                        okListener).setNegativeButton(context.getResources().getString(R.string
                        .cancel), noListener).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    /**
     * @param activity
     * @param requestCode  Need consistent with requestPermission
     * @param permissions
     * @param grantResults
     */
    public static void requestPermissionsResult(final Activity activity, final int requestCode,
                                                @NonNull String[] permissions, @NonNull int[]
                                                        grantResults, PermissionGrant
                                                        permissionGrant) {

        if (activity == null) {
            return;
        }

        if (requestCode == CODE_MULTI_PERMISSION) {
            requestMultiResult(activity, permissions, grantResults, permissionGrant);
            return;
        }

        if (requestCode < 0 || requestCode >= pushLivePermissions.length) {
            return;
        }

        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            permissionGrant.onPermissionGranted(requestCode);

        } else {
            String[] permissionsHint = activity.getResources().getStringArray(R.array
                    .permissions_selectorimg);
            openSettingActivity(activity, permissionsHint[requestCode], permissionGrant);
        }

    }

    private static void openSettingActivity(final Activity activity, String message, final
    PermissionGrant permissionGrant) {

        showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                intent.setData(uri);
                activity.startActivity(intent);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                permissionGrant.onPermissionGranted(CODE_CANCLE);
            }
        });
    }


    /**
     * 获得未授予的权限
     *
     * @param activity
     * @param isShouldRationale true: return no granted and shouldShowRequestPermissionRationale
     *                          permissions,
     *                          false:return no granted and !shouldShowRequestPermissionRationale
     * @return
     */
    public static ArrayList<String> getNoGrantedPermission(Activity activity, boolean
            isShouldRationale) {

        ArrayList<String> permissions = new ArrayList<>();

        for (int i = 0; i < pushLivePermissions.length; i++) {
            String requestPermission = pushLivePermissions[i];
            int checkSelfPermission = -1;
            try {
                checkSelfPermission = ActivityCompat.checkSelfPermission(activity,
                        requestPermission);
            } catch (RuntimeException e) {
//                获取权限情况出现异常
                Toast.makeText(activity, R.string.notPermission, Toast.LENGTH_SHORT).show();
                Log.e(TAG, "RuntimeException:" + e.getMessage());
                return null;
            }
            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                        requestPermission)) {
                    if (isShouldRationale) {
                        permissions.add(requestPermission);
                    }
                } else {
                    if (!isShouldRationale) {
                        permissions.add(requestPermission);
                    }
                }
            }
        }
        return permissions;
    }

}
